package com.usian.admin.gateway.filter;


import com.usian.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author 小万的mate
 * 全局过滤器业务实现
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();   //内部封装了所有http信息，此时已经有数据了
        ServerHttpResponse response = exchange.getResponse();//现在还是个空壳子

        //2.判断当前的请求是否为登录，如果是，直接放行
        //登录接口路径没有token,登完返回的时候才会下发token,不然会进入死循环
        if(request.getURI().getPath().contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }

        //3.获取当前用户的请求头，并取出token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //4.判断token是否为空,就返回给前端错误
        if(StringUtils.isBlank(token)){
            String json = "{\"errorMsg\"}:\"dont have token\"}";
            //通过工厂类重新构建成string字符串返回给前端
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }

        //5.如果令牌存在，解析jwt令牌，判断该令牌是否合法，如果不合法，则向客户端返回错误信息
        Claims claimsBody = AppJwtUtil.getClaimsBody(token); //通过token生成载荷

        if(claimsBody == null){
            String json = "{\"errorMsg\"}:\"dont have invali\"}";
            //通过工厂类重新构建成string字符串返回给前端
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        int claims = AppJwtUtil.verifyToken(claimsBody);   //通过载荷生成token时效

        //校验token时效
        if(claims == 0 || claims == -1){ //-1 有效期还挺长  0 快过期了
            //token有效期操作:
            //获取用户id,方便后面模块操作
            Integer id = (Integer) claimsBody.get("id");
            System.out.println("id-----"+id);
            //将当前用户id设置到token中,使用build重新武装
            ServerHttpRequest build = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId",id + "");
            }).build();
            //扔出交换机，构建
            exchange.mutate().request(build).build();
        }




        //过滤完放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //Ordered: 0 优先级最高
        return 0;
    }
}
